import ExcelJS from 'exceljs';
import FileSaver from 'file-saver';

//
export const exportToExcel = async (data, columns, fileName = 'data.xlsx') => {
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1');

// 设置表头
const headerRow = worksheet.addRow(columns.map(col => col.label));
headerRow.font = { bold: true };

// 遍历数据行
for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
    const rowData = data[rowIndex];
    const rowValues = columns.map(col => {
        if (col.isImage && rowData[col.prop]) {
            return ''; // 图片占位，实际通过addImage插入
        } else {
            return rowData[col.prop] || '';
        }
    });
    worksheet.addRow(rowValues);
}

// 处理图片
const imageColumnIndex = columns.findIndex(col => col.isImage);
if (imageColumnIndex !== -1) {
    for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
        const rowData = data[rowIndex];
        const imgUrls = rowData.imgUrlList || [];

        // 下载所有图片
        const images = await Promise.all(imgUrls.map(async (url) => {
            try {
                const response = await fetch(url);
                const blob = await response.blob();
                const buffer = await blob.arrayBuffer();
                return { buffer, extension: blob.type.split('/')[1] };
            } catch (error) {
                console.error('图片下载失败:', url, error);
                return null;
            }
        }));

        // 插入图片到Excel
        let imageOffsetX = 0;
        for (const image of images.filter(img => img)) {
            const imageId = workbook.addImage({
                buffer: image.buffer,
                extension: image.extension,
            });

            // 定位到对应单元格（行号+1因为第一行是表头）
            worksheet.addImage(imageId, {
                tl: { col: imageColumnIndex, row: rowIndex + 1 },
                br: { col: imageColumnIndex + 1, row: rowIndex + 2 },
                editAs: 'oneCell', // 图片适应单元格
                ext: { width: 100, height: 100 } // 调整图片尺寸
            });
            imageOffsetX += 120; // 调整偏移量以放置多图（可能需要调整行高）
        }

        // 调整行高以适应图片
        const currentRow = worksheet.getRow(rowIndex + 2);
        currentRow.height = 100;
    }
}

// 调整列宽
worksheet.columns.forEach((column, index) => {
    if (columns[index].isImage) {
        column.width = 20;
    } else {
        column.width = columns[index].label.length + 10;
    }
});

// 导出文件
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, fileName);
};
